package com.qf.day6;

/**
 * @date 2022/4/2
 * @desc   观察者
 */
public class Listener2Demo {

    public static void main(String[] args) {
        //创建事件源
        Person person = new Person();
        person.setName("亚柯");
        //注册监听器

        person.addListener(new PersonListener() {
            @Override
            public void doEat(Event e) {
                System.out.println("还吃呢，多胖了都");
            }

            @Override
            public void doSleep(Event e) {
                System.out.println("代码写完了吗，能睡得着吗？");
            }
        });

        //person.sleep();

        person.eat();
    }
}

//事件源
class Person{
    // 要给事件源 注册监听器
    private PersonListener listener;

    private String name;


    public void addListener(PersonListener listener){
        this.listener= listener;
    }


    public void eat(){
        System.out.println(this.getName() + "在吃饭");
        listener.doEat(new Event(this));

    }


    public void sleep(){
        System.out.println(this.getName() + "在睡觉");
        listener.doSleep(new Event(this));
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

interface PersonListener{
    public void doEat(Event e);
    public void doSleep(Event e);
}

class Event{
    // 通过事件对象 可以得到事件源

    private Person source;

    public Event() {
    }

    public Event(Person source) {
        this.source = source;
    }

    public Person getSource() {
        return source;
    }

    public void setSource(Person source) {
        this.source = source;
    }
}